﻿using DataAccess.Api;
using DataAccess.DAL;
using DataAccess.DTO;
using DataAccess.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Web.Controllers
{
    public class AgencyRobotController : BaseController
    {
        //
        // GET: /AgencyRobot/
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public JsonResult GetAgencyRobots()
        {
            AgencyRobotDAL arDal = new AgencyRobotDAL();

            string account = System.Web.HttpContext.Current.Request.Form["account"];
            string content = System.Web.HttpContext.Current.Request.Form["content"];
            int limit = XYD.Common.Request.GetFormInt("limit", 20);
            int offset = XYD.Common.Request.GetFormInt("offset", 1);

            string strWhere = " isdel=0 and PromoterId=@PromoterId ";
            string orderbys = " createtime desc  ";

            if (!string.IsNullOrEmpty(content))
            {
                strWhere += string.Format(" and FlockName like @content ", content);
            }

            if (!string.IsNullOrEmpty(account))
            {
                strWhere += " and au_name like @account ";
            }

            int count = 0;
            List<AgencyRobot> arList = arDal.ListPage(strWhere, orderbys, limit, (offset / limit) + 1, out count, new { account = "%" + account + "%", content = "%" + content + "%", PromoterId=UserSession.user_id });

            //int limit, int offset, int pageSize, int pageNumber

            Result result = new Result();
            result.State = true;
            result.Message = "查询成功";
            result.Datas = new PageData<AgencyRobot> { Total = count, Rows = arList, PageIndex = (offset / limit) + 1, PageSize = limit };

            return Json(result);

        }



        public ActionResult Edit(int id = 0,string ua="")
        {
            ViewBag.timepicker1 = "08:00:00";
            ViewBag.timepicker2 = "22:00:00";
            ViewBag.timepicker3 = "00:00:00";
            ViewBag.timepicker4 = "00:00:00";
            ViewBag.timepicker5 = "00:00:00";
            ViewBag.timepicker6 = "00:00:00";
            //["09:00-12:00","13:00-16:00","18:00-23:00"]

          

            AgencyRobotDAL userDAL = new AgencyRobotDAL();

            AgencyRobot ar;
            if (id != 0)
            {
                ar = userDAL.Get(id);

                if (!string.IsNullOrEmpty(ar.SendTimeStr))
                {
                    string[] timepickers = ar.SendTimeStr.Split(',');

                    ViewBag.timepicker1 = timepickers[0].Split('-')[0];
                    ViewBag.timepicker2 = timepickers[0].Split('-')[1];
                    ViewBag.timepicker3 = timepickers[1].Split('-')[0];
                    ViewBag.timepicker4 = timepickers[1].Split('-')[1];
                    ViewBag.timepicker5 = timepickers[2].Split('-')[0];
                    ViewBag.timepicker6 = timepickers[2].Split('-')[1];

                }




            }
            else
            {

                ar = new AgencyRobot();
                ar.AU_Name = ua;
            }

            return View(ar);
        }
        [HttpPost]
        public JsonResult Edit()
        {




            dynamic obj = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(XYD.Common.Utils.UrlDecode(Request.Form.ToString()));

            AgencyRobotDAL arDal = new AgencyRobotDAL();

            AgencyRobot robot = new AgencyRobot();


            if (int.Parse(obj.id.Value) != 0)
            {
                // if (int.Parse(obj.id.Value) != 1)
                //{
                //    return Json(new Result { State = false, Message = "禁止修改" });
                //}


                robot = arDal.Get(int.Parse(obj.id.Value));

                robot.AU_Name = obj.au_name.Value;
                robot.FlockType = int.Parse(obj.flocktype.Value);
                robot.FlockName = obj.flockname.Value;
                robot.FlockAdmin = obj.flockadmin.Value;
                robot.ImageTextSecond = int.Parse(obj.imagetextsecond.Value);
                robot.FlockSendSecond = int.Parse(obj.flocksendsecond.Value);
                robot.SendTimeStr = string.Format("{0}-{1},{2}-{3},{4}-{5}",
                 obj.timepicker1.Value,
                 obj.timepicker2.Value,
                 obj.timepicker3.Value,
                 obj.timepicker4.Value,
                 obj.timepicker5.Value,
                 obj.timepicker6.Value);
                bool res = arDal.Update(robot);
                if (res)
                {
                    new RobotApiHelper().UpdateAgentConfig(UserSession.user_id.ToString(), robot.AU_Name,robot.FlockName);
                }

                return Json(new Result { State = res, Message = res ? "更新成功" : "更新失败" });

            }
            else
            {
                //判断绑定信息是否存在
                if (!arDal.IsExist(obj.au_name.Value, obj.flockname.Value))
                {
                    AgencyUsersDAL uDal = new AgencyUsersDAL();
                    AgencyUsers userModel = uDal.Get(obj.au_name.Value,UserSession.user_id);
                    if (userModel == null)
                    {
                        return Json(new Result { State = false, Message = "添加失败,代理不存在" });
                    }
                    if (string.IsNullOrEmpty(userModel.wechat_pid))
                        return Json(new Result { State = false, Message = "请先更新pid" });


                    robot.AU_Id = userModel.id;
                    robot.AU_Name = obj.au_name.Value;
                    robot.FlockType = int.Parse(obj.flocktype.Value);
                    robot.FlockName = obj.flockname.Value;
                    robot.FlockAdmin = obj.flockadmin.Value;
                    robot.ImageTextSecond = int.Parse(obj.imagetextsecond.Value);
                    robot.FlockSendSecond = int.Parse(obj.flocksendsecond.Value);
                    robot.ProductType = 0;
                    robot.CreateTime = DateTime.Now;

                    //["09:00-12:00","13:00-16:00","18:00-23:00"]
                    robot.SendTimeStr = string.Format("{0}-{1},{2}-{3},{4}-{5}",
                        obj.timepicker1.Value,
                        obj.timepicker2.Value,
                        obj.timepicker3.Value,
                        obj.timepicker4.Value,
                        obj.timepicker5.Value,
                        obj.timepicker6.Value);

                    robot.alimamaid = userModel.alimamaid;

                    robot.Promoterid = UserSession.user_id;
                    robot.Pid = userModel.wechat_pid;
                    robot.adzoneid = userModel.wechat_adzoneid;
                    bool res = arDal.Insert(robot);
                    if (res)
                    {
                        new RobotApiHelper().AddAgentBind(UserSession.user_id.ToString(), robot.AU_Name, robot.FlockName);
                    }
                    return Json(new Result { State = res, Message = res ? "添加成功" : "添加失败" });
                }
                else
                {
                    return Json(new Result { State = false, Message = "已存在" });
                }

            }


        }
        [HttpPost]
        public JsonResult Delete(int id)
        {

            AgencyRobotDAL arDal = new AgencyRobotDAL();

            if (id != 0)
            {
                var res = arDal.Delete(id);

                return Json(new Result { State = res, Message = res ? "删除成功" : "删除失败" });

            }

            return Json(new Result { State = false, Message = "删除失败" });

        }
    }
}